package sword;

/**
 * @Author: 海琳琦
 * @Date: 2022/5/27 10:35
 */
public class Title42 {

    /**
     * dp问题：下标为i时最大连续和为dp[i]
     * 递推公式：dp[i] = Math.max(nums[i], dp[i - 1] + nums[i]);
     * @param nums
     * @return
     */
    public static int maxSubArray(int[] nums) {
        int n = nums.length;
        int[] dp = new int[n];
        dp[0] = nums[0];
        int max = dp[0];
        for (int i = 1; i < n; i++) {
            dp[i] = Math.max(nums[i], dp[i - 1] + nums[i]);
            if (dp[i] > max) {
                max = dp[i];
            }
        }
        return max;
    }

    public static void main(String[] args) {
        int[] arr = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
        maxSubArray(arr);
    }
}
